//
//  UITextView+Extension.m
//  Weibo - OC
//
//  Created by user on 16/5/2.
//  Copyright © 2016年 user. All rights reserved.
//

#import "UITextView+Extension.h"
#import <YYText/YYText.h>
#import "FANEmoticonViewModel.h"
#import "FANTextAttachment.h"
#import <objc/runtime.h>

static const NSString *KEY = @"EMOTICONTEXT";

@implementation UITextView (Extension)

- (NSMutableString *)emoticonText{
    
    NSMutableString *result = [NSMutableString string];
    
    NSAttributedString *attr = self.attributedText;
    
    [attr enumerateAttributesInRange:NSMakeRange(0, attr.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
       
        if (attrs[@"NSAttachment"] != nil) {
            
            FANTextAttachment *attachment = (FANTextAttachment *)attrs[@"NSAttachment"];
            
            [result appendString:attachment.emoticon.chs];
            
        }else{
            
            [result appendString:[attr.string substringWithRange:range]];
        }
        
    }];
    
//    objc_getAssociatedObject(self, (__bridge const void *)(KEY));
    
    return result;
}

- (void)setEmoticonText:(NSMutableString *)emoticonText{
    
    objc_setAssociatedObject(self, (__bridge const void *)(KEY), self.emoticonText, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)insertEmoticon:(FANEmoticon *)emoticon{
    
    NSMutableAttributedString *originalAttr = [[NSMutableAttributedString alloc] init];
    
    [originalAttr setAttributedString:self.attributedText];
    
    NSString *imageString = [NSString stringWithFormat:@"%@/%@",emoticon.folderName,emoticon.png];
    
    UIImage *image = [UIImage imageNamed:imageString inBundle:[FANEmoticonViewModel sharedEmoticon].bundle compatibleWithTraitCollection:nil];
    
    FANTextAttachment *attachment = [[FANTextAttachment alloc] init];
    
    attachment.image = image;
    
    attachment.emoticon = emoticon;
    
    CGFloat attachHW = [self.font lineHeight];
    
    attachment.bounds = CGRectMake(0, -4, attachHW, attachHW);
    
    NSAttributedString *att = [NSAttributedString attributedStringWithAttachment:attachment];
    
    NSRange selectedRange = self.selectedRange;
    
    [originalAttr replaceCharactersInRange:selectedRange withAttributedString:att];
    
    [originalAttr addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, originalAttr.length)];
    
    self.attributedText = originalAttr;
    
    selectedRange.location += 1;
    
    selectedRange.length = 0;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:nil];
    
    [self.delegate textViewDidChange:self];
}

@end
